<?php
namespace Wap\Controller;
use Think\Controller;
use User\Api\UserApi;
use Wap\Controller\IndexController;
class UserController extends Controller{
   
    private $userapi = '';
    private $www_url = '';
    private $chat_appkey = '';
    private $chat_appsecret = '';
    
    
    public function _initialize(){
        $this->userapi = new UserApi();
        $this->www_url = C('WWW_ROOT');
        $this->chat_appkey = C('appKey');
        $this->chat_appsecret = C('appSecret');
    }
    
    public function index(){
        
    }
    
    /**
     * 卖家登陆接口
     * @param str $username
     * @param str $password     * 
     */
    public function login($username='', $password='', $callback=''){
        if(!empty($callback)){
            $password = base64_decode($password);
        }
        $user_third = $this->userapi->third_login($username, $password);
        if($user_third['id'] > 0){
            $user = $this->third2Local($user_third, $username);
            
            //获取用户的token值，每次登陆获取一次（更换一次）
            vendor('Api.ServerAPI');
            $parm = array('userId'=>$user['id'], 'name' => $user['nickname'], 'portraitUri' => $this->www_url . $user['avatar_url']);
            $p = new \ServerAPI($this->chat_appkey, $this->chat_appsecret);
            $r = $p->getToken($parm['userId'], $parm['name'], $parm['portraitUri']);
            $r = json_decode($r);
            
            $user['token'] = $r->token;
            $user['avatar_url'] = $this->www_url.$user['avatar_url'];
            $data = array(
                'code'  => $user['id'], 
                'msg'   => '登录成功',
                'data'  => $user,
            );
        }else{
            switch ($user_third['id']){
                case -2:
                    $msg = '用户名密码不匹配！';
                    break;
                case -3:
                    $msg = $user_third['msg'];
                    break;
                default :
                    $third_id = 0;
                    $msg = '登录失败';
            }
            $data = array('code' => $user_third['id'], 'msg' => $msg);
        }
        if(empty($callback)){
            $this->ajaxReturn($data);
        }else{
            jsonP($data, $callback);
        }
    }
    
    /**
     * 卖家登录后对本地操作
     * 包括对本地用户表操作，商家表操作，以及更新用户登录信息
     * @param type $id 第三方用户表id
     * @param type $username 用户名
     * @return int 用户表id
     */
    private function third2Local($user_third, $username){

        //判断该第三方用户是否存在本地数据库
        if($user = M('User')->field('id,avatar_url,nickname,usertype,status')->where(array('third_id' => $user_third['id']))->find()){
            $uid = $user['id'];
            M('User')->save(array('last_login_time' => NOW_TIME, 'id' => $uid)); //更新本地数据库登录信息
            M('User_seller')->where(array('uid' => $uid))->save(
                array(
                    'rank'      => $user_third['rank'], 
                    'user_type' => $user_third['user_type']
                )
            );
        }else{
            //随机获取头像和背景图
            $avatar = C('DEFAULT_AVATAR') . 'avatar(' . rand(1, 8) . ').jpg';
            $bg = C('DEFAULT_BACKGROUND') . 'bg(' . rand(1, 21) . ').jpg';
            //在本地数据库中新增用户
            $data = array(
                'third_id'          => $user_third['id'],
                'last_login_time'   => NOW_TIME,
                'reg_time'          => NOW_TIME,
                'nickname'          => $username,
                'username'          => 'laoA_'.$username,
                'realname'          => $user_third['realname'],
                'avatar_url'        => $avatar,
                'cover_img'         => $bg,
                'usertype'          => 1,
                'status'            => 1,
            );
            $uid = M('User')->add($data); //在本地用户表添加数据
            $user = array('id' => $uid, 'avatar_url' => $avatar, 'nickname' => $username, 'usertype' => 1, 'status' => 1);
            
            //新增卖家用户
            $seller = array(
                'uid'       => $uid, 
                'nickname'  => $username,
                'rank'      => $user_third['rank'],
                'user_type' => $user_third['user_type'],
            );
            M('User_seller')->add($seller);

            //卖家基本权限设定,暂时写死设定权限：2
            M('Auth_group_access')->add(array('uid' => $uid, 'group_id' => 2));            
        }
        return $user;
    }
    
    
}